<?php
/**
 * 控制器基类-带权限验证
 * User: linhui
 * Date: 2016/12/14
 * Time: 0:47
 */

namespace Admin\Controller;


use Common\Lib\SessionRedis;

class BaseController extends BasicController
{
    /**
     * @var array 后台用户登录信息
     */
    protected $user;
    /**
     * @var string 列表页查询字段
     */
    protected $listField = '*';

    /**
     *初始化
     */
    public function _initialize() {

        //获取登录信息 未登录直接跳转到登录
        if(!$this->user = getLoginInfo()){
            $this->redirect('Public/login');
            exit();
        }
        //获取菜单与面包屑
        list($menus, $bread_crumb) = $this->initMenu();

        $this->assign('menuList', $menus);
        $this->assign('bread_crumb', $bread_crumb);

        //权限验证
        $uri = MODULE_NAME .'/'. CONTROLLER_NAME .'/'. ACTION_NAME;
        //不检查的路由
        $no_check = array(
            'Admin/Index/index',
        );

        if(!in_array($uri, $no_check) && !authCheck($uri, $this->user['user_id'])){
            $this->error('您没有权限');
            exit;
        }
    }



    /**
     * 编辑通用
     * @param string $model
     */
    public function edit($model = '')
    {
        $model = $model ? D($model): D(CONTROLLER_NAME);

        $pk = $model->getPk();
        $id = I($pk, 0, 'intval');
        $info = $model->find($id);
        if(IS_POST){
            $data = I('post.');
            if(method_exists($this, 'saveDataTrans')){
                $this->saveDataTrans($data, $model);
            }
            $data = $model->create($data);

            if($data && $data[$pk] ? $model->save() !== false : $model->add()){
                $this->responseAjax('保存成功', true, '', U('index'));
            } else {
                $this->responseAjax('保存失败', false);
            }
        }
        if(method_exists($this, 'beforeEdit')){
            $this->beforeEdit($model, $info);
        }
        $this->assign('info', $info);
        $this->display();
    }

    /**
     * 列表页通用
     * @param string $model
     */
    public function index($model = '')
    {
        $model_name = $model ? $model : CONTROLLER_NAME;

        if(IS_POST && is_array(I('sort'))){
            $this->sort(D($model_name));
        }
        if (method_exists($this, 'getSort')) {
           $sort = $this->getSort('index');
        }
        $map = array();
        list($list, $page) = $this->_list($model_name, $map, $sort);

        $this->assign('start_offset', $page->firstRow);
        $this->assign('list', $list);
        $this->assign('page', $page->show());
        $this->display();
    }

    /**
     * 通用排序
     * @param $model
     */
    public function sort($model)
    {
        if(IS_POST){
            $data = I('post.');
            $pk = $model->getPk();
            $count = 0;
            foreach($data['sort'] as $sort){
                $model->where(array($pk=>$sort['id']))->save(array('sort'=>$sort['sort'])) !== false && $count++;
            }
            if($count){
                $this->responseAjax('排序成功', true, array(), U('index'));
            }
            $this->responseAjax('排序失败');
        }
    }

    /**
     * 查询列表
     * @param string $model_name 数据模型
     * @param array $map 条件
     * @param string $sort 排序
     * @param int $pageSize 分页条数
     * @return array
     */
    public function _list($model_name, $map = array(), $sort = '', $pageSize = 0)
    {
        $model = D($model_name);
        $pageSize = $pageSize ? $pageSize : C('DEFAULT_PAGE_SIZE');

        if(method_exists($this, '_filter')){
            $map = array_merge($map, $this->_filter($model));
        }
        $total = $model->where($map)->count();
        $page = new \Think\Page($total, $pageSize);
        $page_config = C('PAGE_CONFIG');
        foreach($page_config as $key => $config){
            $page->setConfig($key, $config);
        }
        $list = $model->where($map)
            ->order($sort)
            ->field($this->listField)
            ->limit($page->firstRow, $pageSize)
            ->select();

        if(method_exists($this, 'indexCallback')){
            $this->indexCallback($list, $map);
        }

        return array($list, $page);
    }

    /**
     * 通用过滤
     * @param $model \Think\Model
     * @return array
     */
    public function _filter($model)
    {
        $fields = $model->getDbFields();
        $map = array();
        $request = I('request.');
        //逐个对应条件
        foreach($request as $key => $item) {
            if (in_array($key, $fields) && !is_array($item) && $item !== null && $item !== '') {
                $map[$key] = $item;
            }
        }
        //模糊查询
        if(is_array($request['like'])) {
            foreach($request['like'] as $key => $item) {
                if($item){
                    $map[$key] = array('like', "%{$item}%");
                }
            }
        }
        $this->assign('map', $request);
        return $map;
    }

    /**
     * 删除通用
     * @param string $model
     */
    public function del($model = ''){
        $model = $model ? D($model) : D(CONTROLLER_NAME);
        $pk = $model->getPk();
        $id = I($pk, 0, 'intval');
        if($model->delete($id) !== false){
            $this->responseAjax('删除成功', true, array(), U('index'));
        } else{
            $this->responseAjax('删除失败', false);
        }
    }

    /**
     *禁用/启用
     */
    public function ban($model = '')
    {
        $model = $model ? D($model) : D(CONTROLLER_NAME);
        $pk = $model->getPk();
        $id = I($pk, 0, 'intval');
        $status = I('status', 0, 'intval');
        if($model->where(array($pk=>$id))->save(array('status'=>$status))){
            $this->responseAjax('操作成功', true, array(), U('index'));
        } else{
            $this->responseAjax('操作失败');
        }
    }
}
